import { Base } from '../../utils/base.js';

var base = new Base();

class Order extends Base {

  constructor() {
    super();
    this._storageKeyName = 'newOrder';
  }

  // 下单
  doOrder(param, callback){
    var that = this;
    var allParams = {
      url: 'order/place',
      method: 'POST',
      data: {
        products: param
      },
      sCallBack: function(data){
        that.execSetStorageSync(true);
        callback && callback(data);
      },eCallback: function(){

      }
    };
    this.request(allParams);
  }

  // 更新订单缓存
  execSetStorageSync(data){
    wx.setStorageSync(this._storageKeyName, data);
  }

  // 获取用户订单列表
  getOrders(pageIndex, callback){
    
    var allParams = {
      url: 'order/by_user',
      data: { page: pageIndex },
      type: 'get',
      sCallBack: function (res) {
        callback && callback(res.data)
      }
    };
    this.request(allParams);
  }

  // 获取订单详情
  getOrderInfoByID(id, callback){
    var params = {
      url: 'order',
      method: 'GET',
      data: {
        id: id,
      },
      sCallBack: function (res) {
        callback && callback(res);
      }
    }
    this.request(params);
  }

  // 支付
  execPay(id, callback){
    var that = this;
    var params = {
      url: 'pay',
      method: 'POST',
      data: {
        id: id,
      },
      sCallBack: function (preData) {
        if (preData.timeStamp){
          wx.requestPayment({
            timeStamp: preData.timeStamp,
            nonceStr: preData.nonceStr,
            package: preData.package,
            signType: preData.signType,
            paySign: preData.paySign,
            success: function (res) {
              callback && callback(2)
            }, fail: function (res) {
              callback && callback(1)
            }
          })
        }else{
          callback && callback(0)
        }
      }
    };
    this.request(params);
  }

  // 检测是否有新订单
  hasNewOrder(){
    var flag = wx.getStorageSync(this._storageKeyName);
    return flag == true;
  }

}
export { Order }